import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/collect/add_collect/index.dart";
import "package:ct_pa_majordomo/pages/device/collect/api.dart";
import "package:ct_pa_majordomo/pages/device/collect/detail/index.dart";
import "package:ct_pa_majordomo/pages/device/collect/widgets/list_item.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";

class Collect extends StatefulWidget {
  const Collect({super.key});

  @override
  State<StatefulWidget> createState() => _CollectState();

}

class _CollectState extends State<Collect> {
  final ScrollController _scrollController = ScrollController();
  final Map _filter = { "pageNum": 1 };
  List _groups = [];
  List _list = [];
  int _total = 0;
  bool _isLoading = false;
  final Map _resData = {
    "total": 2,
    "rows": [{"id": 1, "name": "泰寓A102"}, {"id": 2, "name": "泰寓A103"}],
  };
  final List<FilterHeaderItem> _headerItems = [
    FilterHeaderItem(title: "分组"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];

  Future<void> _getGroups() async {
    try {
      // EasyLoading.show();
      List resData = await apartmentApi.getGroups();
      // EasyLoading.dismiss();
      setState(() => _groups = resData..insert(0, {"groupName": "全部"}));
    } catch (error) {
      print(error);
    }
  }

  Future<void> _getLockList() async {
    try {
      Map<String, dynamic> params = {..._filter, "pageSize": 10};
      _isLoading = true;
      Map resData = await collectApi.getCollects(params);
      _isLoading = false;
      List data = resData["rows"] ?? [];
      setState(() {
        _total = resData["total"];
        _headerItems.last.title = "数量：$_total";
        _list.addAll(data);
      });
    } catch (error) {
      print(error);
    }
  }


  Future<void> _onRefresh() async {
    setState(() {
      _filter["pageNum"] = 1;
      _list = [];
    });
    _getLockList();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _filter["pageNum"] += 1;
        _getLockList();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getGroups();
    _getLockList();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "采集器",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      onSearch: (value) {
        print("最外层组件的：$value");
        setState(() {
          _filter["pageNum"] = 1;
          _filter["name"] = value;
        });
        _getLockList();
      },
      showFloatBtn: true,
      floatOnPress: () {
        Stacker.pushNamed(Keys.DEVICE_COLLECT_ADD).then((value){
          if (value != null) {
            if (value as bool) _onRefresh();
          }
        });
      },
      children: [
        FilterLayout(
          headerItems: _headerItems,
          dropdownItems: [
            FilterDropdownItem(
              items: _groups,
              itemAsString: (item) => item["groupName"],
              compare: (item) => item["groupId"] == _filter["groupId"],
              onChanged: (item) => setState(() {
                _filter["groupId"] = item["groupId"];
              }),
            ),
          ],
          child: RefreshIndicator(
            onRefresh: _onRefresh,
            child: _list.isEmpty ? ListView(
              children: [ EmptyData(), ],
            ) : ListView.separated(
              controller: _scrollController,
              physics: const AlwaysScrollableScrollPhysics(),
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              itemBuilder: (context, index) {
                return GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Stacker.pushNamed(Keys.DEVICE_COLLECT_DETAIL, arguments: _list[index]["collectId"],)
                        .then((refresh) {
                          if (refresh != null && refresh as bool) {
                            _onRefresh();
                          }
                    });
                  },
                  child: ListItem(collect: _list[index]),
                );
              },
              separatorBuilder: (context, index) => const SizedBox(height: 15),
              itemCount: _list.length,
            ),
          ),
        ),
      ],
    );
  }

}